package com.xxjh.brs.mvc.track.filter;

import com.xxjh.brs.mvc.track.MdcUtil;
import com.xxjh.brs.mvc.track.ThreadMdcUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.xxjh.brs.mvc.track.MdcUtil.TRACE_ID;

public class TracerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String traceId = request.getHeader(TRACE_ID);
        if (traceId == null || "".equals(traceId)) {
            traceId = MdcUtil.generateUuId();
        }
        ThreadMdcUtil.setTraceId(traceId);
        // 响应头设置tid
        if (servletResponse instanceof HttpServletResponse) {
            ((HttpServletResponse) servletResponse).addHeader(TRACE_ID, MdcUtil.getTraceId());
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        MdcUtil.removeTraceId();
    }
}